home *** CD-ROM | disk | FTP | other *** search
- Imports System.Globalization
- Imports System.IO
- Imports Microsoft.Win32
-
- Module MainModule
-
- Sub Main()
- ' Run one of the Textxxxx procedures below by uncommenting only one statement
-
- 'TestFileDirectory()
- 'TestFileDirectoryInfo()
- 'TestPath()
- 'TestStreamReader()
- 'TestStreamWriter()
- 'TestBinaryReaderWriter()
- 'TestMemoryStream()
- 'TestStringReaderWriter()
- 'TestCustomBinaryReaderWriter()
-
- ' These statements are usuful when running inside Visual Studio.NET
- Console.WriteLine("")
- Console.WriteLine(">>> Press Enter to terminate the program <<<")
- Console.ReadLine()
- End Sub
-
- ' this procedure tests the File and Directory objects
-
- Sub TestFileDirectory()
- ' Save the current directory.
- Dim currDir As String = Directory.GetCurrentDirectory
- ' Change the current directory to something else.
- Directory.SetCurrentDirectory("C:\")
- ' check that it worked
- Console.WriteLine("Current directory: " & Directory.GetCurrentDirectory)
- ' Restore the current directory.
- Directory.SetCurrentDirectory(currDir)
-
- ' Retrieve all the root paths.
- Dim strRoots() As String = Directory.GetLogicalDrives
- Dim s As String
- For Each s In strRoots
- Console.WriteLine(s) ' => C:\ D:\ ...
- Next
-
- ' display files and directories in C:\DOCS
- PrintDirTree("c:\docs", True)
-
- ' Display all the *.txt files in C:\DOCS.
- Dim fname As String
- For Each fname In Directory.GetFiles("c:\docs", "*.txt")
- Console.WriteLine(fname)
- Next
- Console.WriteLine("")
-
- ' Display system and hidden files in C:\.
- For Each fname In Directory.GetFiles("C:\")
- Dim attr As FileAttributes = File.GetAttributes(fname)
- ' Show the file if it is marked as either hidden or system (or both).
- If CBool(attr And FileAttributes.Hidden) Or CBool(attr And FileAttributes.System) Then
- ' NOTE: you can make the IF condition more concise as follows:
- 'If CBool(attr And (FileAttributes.Hidden Or FileAttributes.System)) Then
- Console.WriteLine(fname)
- End If
- Next
-
- ' ensure that we aren't destroying an existing directory tree
- If Not Directory.Exists("c:\myapp") Then
- ' Next line works even if the C:\MyApp directory doesn't exist yet.
- Directory.CreateDirectory("C:\MyApp\Data")
- ' check that it worked
- If Directory.Exists("c:\myapp\data") Then
- Console.WriteLine("The C:\MYAPP\DATA directory has been created.")
- End If
- ' delete it, forcing deletion of inner directories
- Directory.Delete("c:\MyApp", True)
- End If
-
- ' Change the access date-time of all files in C:\DOCS.
- For Each fname In Directory.GetFiles("c:\docs", "*.txt")
- File.SetLastAccessTime(fname, Date.Now)
- Next
-
- ' a "touch" utility
- ' NOTE: test by running from command prompt and passing one more more file names
- For Each fname In Environment.GetCommandLineArgs
- File.SetCreationTime(fname, Date.Now)
- Next
- End Sub
-
- ' traverse a directory tree
-
- Sub PrintDirTree(ByVal dir As String, ByVal showFiles As Boolean, _
- Optional ByVal level As Integer = 0)
- Dim subdir As String
- Dim fname As String
-
- ' Display the name of this directory with correct indentation.
- Console.WriteLine(New String("-"c, level * 2) & dir)
-
- Try
- ' Display all files in this directory, with correct indentation.
- If showFiles Then
- For Each fname In Directory.GetFiles(dir)
- Console.WriteLine(New String(" "c, level * 2 + 2) & fname)
- Next
- End If
- ' A recursive call for all the subdirectories in this directory.
- For Each subdir In Directory.GetDirectories(dir)
- PrintDirTree(subdir, showFiles, level + 1)
- Next
- Catch
- ' Do nothing if any error (presumably "Drive not ready").
- End Try
- End Sub
-
- ' test DirectoryInfo or FileInfo classes
-
- Sub TestFileDirectoryInfo()
- ' Create a DirectoryInfo object that points to C:\.
- Dim rootDi As New DirectoryInfo("C:\")
- ' Create a FileInfo object that points to C:\Autoexec.bat.
- Dim fi As New FileInfo("C:\Autoexec.bat")
-
- ' List the directories in C:\.
- Dim di As DirectoryInfo
- For Each di In rootDi.GetDirectories
- Console.WriteLine(di.Name)
- Next
- Console.WriteLine("")
-
- ' List all the *.txt files in C:\.
- For Each fi In rootDi.GetFiles("*.txt")
- Console.WriteLine(fi.Name)
- Next
- Console.WriteLine("")
-
- Dim fsi As FileSystemInfo
-
- ' Display all files and subdirectories in C:\
- ' Note that we can create the DirectoryInfo object on-the-fly.
- For Each fsi In (New DirectoryInfo("C:\")).GetFileSystemInfos
- ' Use a [dir] or [file] prefix.
- If CBool(fsi.Attributes And FileAttributes.Directory) Then
- Console.Write("[dir] ")
- Else
- Console.Write("[file] ")
- End If
- ' Print name and creation date
- Console.WriteLine(fsi.Name & " - " & fsi.CreationTime)
- Next
- End Sub
-
- ' this procedure tests the Path class
-
- Sub TestPath()
- Console.WriteLine(Path.AltDirectorySeparatorChar) ' => /
- Console.WriteLine(Path.DirectorySeparatorChar) ' => \
- Console.WriteLine(Path.InvalidPathChars) ' => "<>|
- Console.WriteLine(Path.PathSeparator) ' => ;
- Console.WriteLine(Path.VolumeSeparatorChar) ' => :
-
- ' Note that paths are in 8.3 MsDos format.
- Console.WriteLine(Path.GetTempPath)
- ' => C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\
- Console.WriteLine(Path.GetTempFileName)
- ' => C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\tmp1B2.tmp
-
- Dim fil As String = "C:\MyApp\Bin\MyApp.exe"
- Console.WriteLine(Path.GetDirectoryName(fil)) ' => C:\MyApp\Bin
- Console.WriteLine(Path.GetFileName(fil)) ' => MyApp.exe
- Console.WriteLine(Path.GetExtension(fil)) ' => .exe
- Console.WriteLine(Path.GetFileNameWithoutExtension(fil)) ' => MyApp
- Console.WriteLine(Path.GetPathRoot(fil)) ' => C:\
- Console.WriteLine(Path.HasExtension(fil)) ' => True
- Console.WriteLine(Path.IsPathRooted(fil)) ' => True
-
- ' Next line assumes that current directory is C:\MyApp.
- Console.WriteLine(Path.GetFullPath("MyApp.Exe")) ' => C:\MyApp\MyApp.Exe
-
- Console.WriteLine(Path.ChangeExtension("MyApp.Exe", "Dat")) ' => MyApp.Dat
-
- Console.WriteLine(Path.Combine("C:\MyApp\", "MyApp.Dat"))
- ' => C:\MyApp\MyApp.Dat
- End Sub
-
- ' this procedure tests StreamReader objects
-
- Sub TestStreamReader()
- ' The File.OpenText shared method.
- Dim sr As StreamReader = File.OpenText("c:\autoexec.bat")
-
- ' the following block of code include alternative
- ' open tecniques , as described in the book
-
- #If False Then
- ' The OpenText instance method of a FileInfo object.
- Dim fi2 As New FileInfo("c:\autoexec.bat")
- Dim sr2 As StreamReader = fi2.OpenText
-
- ' By passing a FileStream from the Open method of File class to
- ' the StreamReader's constructor method.
- ' (This technique lets you specify mode, access, and share mode.)
- Dim st3 As Stream = File.Open("C:\autoexec.bat", _
- FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
- Dim sr3 As New StreamReader(st3)
-
- ' By opening a FileStream on the file, and then passing it
- ' to the StreamReader's constructor method.
- Dim fs4 As New FileStream("C:\autoexec.bat", FileMode.Open)
- Dim sr4 As New StreamReader(fs4)
-
- ' By getting a FileStream from the OpenRead method of File class
- ' and passing it to the StreamReader's constructor.
- Dim sr5 As New StreamReader(File.OpenRead("c:\autoexec.bat"))
-
- ' By passing the file name to the StreamReader's constructor.
- Dim sr6 As New StreamReader("c:\autoexec.bat")
-
- ' By passing the file name and encoding.
- Dim sr7 As New StreamReader("c:\autoexec.bat", System.Text.Encoding.Unicode)
- Dim sr8 As New StreamReader("c:\autoexec.bat", System.Text.Encoding.ASCII)
- ' As before, but we let the system decide the best encoding.
- Dim sr9 As New StreamReader("c:\autoexec.bat", True)
- #End If
-
- ' Display all the text lines in the file.
- Do Until sr.Peek = -1
- ' The ReadLine methods reads whole lines.
- Console.WriteLine(sr.ReadLine)
- Loop
- ' Always close a StreamReader when you've done with it.
- sr.Close()
-
- ' Read the entire contents of C:\Autoexec.bat in one shot.
- sr = New StreamReader("c:\autoexec.bat")
- Dim fileContents As String = sr.ReadToEnd()
- Console.WriteLine(fileContents)
- Console.WriteLine("")
-
- ' If the file contains "WARNING" then process it again, one character at a
- ' time (admittedly a silly thing to do, but it's just a demo).
- If fileContents.Length >= 10 Then
- ' Reset the stream's pointer to the beginning.
- sr.BaseStream.Seek(0, SeekOrigin.Begin)
- ' Read individual characters until EOF is reached.
- Do Until sr.Peek() = -1
- ' Read returns an integer, convert it to Char.
- Console.Write(sr.Read.ToString)
- Loop
- End If
- sr.Close()
- Console.WriteLine("")
- End Sub
-
- ' this procedure tests StreamWriter objects
-
- Sub TestStreamWriter()
-
- ' skip over alternative open tecniques in this demo
- #If False Then
- ' The File class's CreateText or AppendText methods (shared or instance).
- Dim sw1 As StreamWriter = File.CreateText("c:\temp.dat")
-
- ' By passing a FileStream from the Open method of File class to
- ' the StreamWriter's constructor method.
- Dim st2 As Stream = File.Open("C:\temp.dat", _
- FileMode.Create, FileAccess.ReadWrite, FileShare.None)
- Dim sw2 As New StreamWriter(st2)
-
- ' By opening a FileStream on the file, and then passing it
- ' to the StreamWriter's constructor method.
- Dim fs3 As New FileStream("C:\autoexec.bat", FileMode.Open)
- Dim sw3 As New StreamWriter(fs3)
-
- ' By getting a FileStream from the OpenWrite method of File class
- ' and passing it to the StreamWriter's constructor.
- Dim sw4 As New StreamWriter(File.OpenWrite("C:\temp.dat"))
-
- ' By passing the file name to the StreamWriter's constructor.
- Dim sw5 As New StreamWriter("C:\temp.dat")
- #End If
-
- ' Copy C:\Autoexec.bat to C:\Autoexec.new, and covert chars to uppercase.
- Dim sr As New StreamReader("C:\Autoexec.bat")
- Dim sw As New StreamWriter("C:\Autoexec.new")
-
- Do Until sr.Peek = -1
- ' The ReadLine method returns a string, so we can
- ' convert it to uppercase on the fly.
- sw.WriteLine(sr.ReadLine.ToUpper)
- Loop
- sr.Close()
- sw.Close() ' This actually writes data to file and closes it.
-
- ' do it again in one operation
- sr = New StreamReader("C:\Autoexec.bat")
- sw = New StreamWriter("C:\Autoexec.new")
- sw.Write(sr.ReadToEnd.ToUpper)
- sr.Close()
- sw.Close()
- End Sub
-
- ' this procedure tests the BinaryReader and BinaryWriter classes
-
- Sub TestBinaryReaderWriter()
- ' Associate a stream to a new file, opened with write access.
- Dim st As Stream = File.Open("c:\values.dat", FileMode.Create, FileAccess.Write)
- ' Create a BinaryWriter associated to the output stream.
- Dim bw As New BinaryWriter(st)
-
- Dim i As Integer, rand As New Random()
- For i = 1 To 10
- bw.Write(rand.NextDouble)
- Next
- ' Flush the output data to the file.
- bw.Close()
- st.Close()
-
- ' Read back values written in previous example.
-
- ' Associate a stream to an existing file, opened with read access.
- Dim st2 As Stream = File.Open("c:\values.dat", FileMode.Open, FileAccess.Read)
- ' Create a BinaryReader associated to the input stream.
- Dim br2 As New BinaryReader(st2)
-
- ' Loop until there is data avaialble.
- Do Until br2.PeekChar = -1
- ' Read the next element.
- Console.WriteLine(br2.ReadDouble)
- Loop
- br2.Close()
- st2.Close()
- End Sub
-
- ' this procedure tests the MemoryStream object
-
- Sub TestMemoryStream()
- ' Create a memory stream with initial capacity of 1K.
- Dim st As New MemoryStream(1024)
- Dim bw As New BinaryWriter(st)
- Dim i As Integer, rand As New Random()
- ' Write 10 random Double values to the stream.
- For i = 1 To 10
- bw.Write(rand.NextDouble)
- Next
-
- ' Rewind the stream to the beginning.
- st.Seek(0, SeekOrigin.Begin)
- Dim br As New BinaryReader(st)
-
- Do Until br.PeekChar = -1
- Console.WriteLine(br.ReadDouble)
- Loop
- br.Close()
- st.Close()
-
- ' Write two strings to a MemoryStream.
- st = New MemoryStream(1000)
- bw = New BinaryWriter(st)
- bw.Write("length-prefixed string")
-
- ' we'll use for both reading and writing
- Dim buffer(1024) As Char 'a 1K buffer
-
- Dim s As String = "13 Characters" ' fixed-length string
- s.CopyTo(0, buffer, 0, 13) ' copy into the buffer
- bw.Write(buffer, 0, 13) ' output first 13 chars in buffer
- bw.Write(buffer, 0, 13) ' do it twice
-
- ' Rewind the stream, and prepare to read from it.
- st.Seek(0, SeekOrigin.Begin)
- br = New BinaryReader(st)
- ' Reading the length-prefixed string is easy.
- Console.WriteLine(br.ReadString) ' => length-prefixed string
-
- ' Read the fixed-length string into the buffer
- br.Read(buffer, 0, 13) ' Read 13 characters.
- s = New String(buffer, 0, 13) ' convert to a string
- Console.WriteLine(s) ' => 13 Characters
-
- ' Another way to read a fixed-length string
- s = New String(br.ReadChars(13))
- Console.WriteLine(s) ' => 13 Characters
- End Sub
-
- ' this procedure tests StringReader and StringWriter classes
-
- Sub TestStringReaderWriter()
- Dim veryLongString As String
- ' initialize this variable with the contents of Autoexec.bat
- Dim sr As New StreamReader("c:\autoexec.bat")
- veryLongString = sr.ReadToEnd
- sr.Close()
-
- ' The veryLongString variable contains the text to parse.
- Dim strReader As New StringReader(veryLongString)
- ' Display individual lines of text.
- Do Until strReader.Peek = -1
- Console.WriteLine(strReader.ReadLine)
- Loop
-
- ' Create a string with the space-separated abbreviated names of weekdays.
- ' A StringBuilder of 7*4 characters is enough.
- Dim sb As New System.Text.StringBuilder(28)
- ' The StringWriter associated to the StringBuilder.
- Dim strWriter As New StringWriter(sb)
-
- ' Output day names to the string.
- Dim d As String
- For Each d In DateTimeFormatInfo.CurrentInfo.AbbreviatedDayNames
- strWriter.Write(d)
- strWriter.Write(" ") ' Append a space.
- Next
- Console.WriteLine(sb) ' => Sun Mon Tue Wed Thu Fri Sat
- End Sub
-
- ' this procedure tests custom BinaryReaderEx and BinaryWriterEx classes
-
- Sub TestCustomBinaryReaderWriter()
- Dim st As New MemoryStream(1000)
- Dim bw As New BinaryWriterEx(st)
-
- ' Write a Person object, then a รป1 value (short).
- Dim p As New Person("Joe", "Doe")
- bw.Write(p)
- bw.Write(-1S)
-
- ' Rewind the stream, and prepare to read from it.
- st.Seek(0, SeekOrigin.Begin)
- Dim br As New BinaryReaderEx(st)
-
- ' Read a Person object, and prove that properties have been preserved.
- Dim p2 As Person = br.ReadPerson()
- Console.WriteLine(p.FirstName & " " & p.LastName)
- ' Read the Short value.
- Console.WriteLine(br.ReadInt16)
-
- ' Clean up
- bw.Close()
- br.Close()
- st.Close()
- End Sub
-
- End Module
-